package twt.practice.votingsystem.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import twt.practice.votingsystem.dao.StudentMapper;
import twt.practice.votingsystem.service.StudentService;
import twt.practice.votingsystem.utils.APIResponse;

import java.util.concurrent.locks.ReentrantLock;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    StudentMapper studentMapper;

    private static ReentrantLock lock = new ReentrantLock();

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse register(String student_name, String password){
        lock.lock();
        try{
            return APIResponse.success(studentMapper.register(student_name, password));
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500,"注册失败");
        }finally {
            lock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse login(String student_name, String password){
        lock.lock();
        try{
            return APIResponse.success(studentMapper.login(student_name, password));
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(500,"登录失败");
        }finally {
            lock.unlock();
        }
    }

}
